package test.chat.client.websockets;

import org.fusesource.restygwt.client.JsonEncoderDecoder;

import test.chat.common.command.Command;

import com.google.gwt.core.client.GWT;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.websockets.client.WebSocket;
import com.google.gwt.websockets.client.WebSocketCallback;

public class ChatService implements WebSocketCallback {
    private final WebSocket webSocket = new WebSocket(this);

    private CompletionHandler connectHandler;

    private CompletionHandler disconnectHandler;

    private ClientCommandHandler commandHandler;

    public void setCommandHandler(ClientCommandHandler commandHandler) {
        this.commandHandler = commandHandler;
    }

    public void connect(CompletionHandler connectHandler) {
        this.connectHandler = connectHandler;

        webSocket.connect("ws://localhost:8765/chatWebSocket");
    }

    public void disconnect(CompletionHandler disconnectHandler) {
        this.disconnectHandler = disconnectHandler;

        webSocket.close();
    }

    @Override
    public void onConnect() {
        connectHandler.onComplete();
    }

    @Override
    public void onDisconnect() {
        if(disconnectHandler != null) {
            disconnectHandler.onComplete();
        } else {
            commandHandler.onUnexpectedDisconnect();
        }
    }

    @Override
    public void onMessage(String message) {
        JsonEncoderDecoder<Command> codec = GWT.create(CommandCodec.class);

        Command command = codec.decode(JSONParser.parseLenient(message));

        commandHandler.onCommand(command);
    }

    public void sendCommand(Command command) {
        JsonEncoderDecoder<Command> codec = GWT.create(CommandCodec.class);

        webSocket.send(codec.encode(command).toString());
    }
}
